import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:get/get.dart';

import '../../../../common/utils/index.dart';
import '../../../../common/values/index.dart';
import '../../../../common/widgets/index.dart';
import 'index.dart';

class CmsDocumentPage extends GetView<CmsDocumentController> {
  @override
  final String? tag;
  const CmsDocumentPage({Key? key, required this.tag}) : super(key: key);

  static Future<void> open(String documentId,
      {String title = '',
      Map<String, dynamic>? options,
      bool isCloseCurrentPage = false}) async {
    Get.lazyPut<CmsDocumentController>(() => CmsDocumentController(),
        tag: documentId);
    if (isCloseCurrentPage) {
      await Get.off(CmsDocumentPage(tag: documentId), arguments: {
        "documentId": documentId,
        "title": title,
        "options": options
      });
    } else {
      await Get.to(CmsDocumentPage(tag: documentId), arguments: {
        "documentId": documentId,
        "title": title,
        "options": options
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<CmsDocumentController>(
      tag: tag,
      builder: (_) {
        return Scaffold(
          appBar: AppBar(
              leading: IconButton(
                icon: const Icon(Icons.arrow_back),
                onPressed: () => {controller.tapBackBtn()},
              ),
              title: Obx(() => Text(controller.state.title)),
              actions: [O2UI.webviewPopupMenu(() => controller.copyLink())]),
          body: SafeArea(
            child: Obx(() => controller.state.url.isEmpty
                ? const Center(child: CircularProgressIndicator())
                : _buildView()),
          ),
        );
      },
    );
  }

  // 主视图
  Widget _buildView() {
    return InAppWebView(
        key: controller.webViewKey,
        initialUrlRequest: URLRequest(url: Uri.parse(controller.state.url)),
        initialOptions: InAppWebViewGroupOptions(
            crossPlatform: InAppWebViewOptions(
                useShouldOverrideUrlLoading: true,
                useOnDownloadStart: true,
                javaScriptCanOpenWindowsAutomatically: true,
                mediaPlaybackRequiresUserGesture: false,
                applicationNameForUserAgent: O2.webviewUserAgent),
            android: AndroidInAppWebViewOptions(
              useHybridComposition: true,
              supportMultipleWindows: true,
            ),
            ios: IOSInAppWebViewOptions(
              allowsInlineMediaPlayback: true,
            )),
        onWebViewCreated: (c) {
          controller.setupWebviewJsHandler(c);
        },
        // onCreateWindow: (c, createWindowRequest) async {
        //   OLogger.d("创建新窗口，，，，${createWindowRequest.request.url}");
        // },
        shouldOverrideUrlLoading: (c, navigationAction) async {
          var uri = navigationAction.request.url!;
          OLogger.d("shouldOverrideUrlLoading uri: $uri");
          // c.loadUrl(urlRequest: URLRequest(url: uri));
          return NavigationActionPolicy.ALLOW;
        },
        onProgressChanged: (c, p) {
          controller.progressChanged(c, p);
        },
        // h5下载文件
        onDownloadStartRequest: (c, request) async {
          controller.webviewHelper.onFileDownloadStart(request);
        },
        onTitleChanged: ((c, title) {
          OLogger.d('修改网页标题： $title');
          if (title != null && title.isNotEmpty) {
            controller.state.title = title;
          }
        }),
        onConsoleMessage: (c, consoleMessage) {
          OLogger.i("console: $consoleMessage");
        });
  }
}
